# test_DescribeAccountQuota.py
import pytest


class TencentCloudCVMClient:
    def describe_account_quota(self, region, filters=None):
        # 参数类型校验
        if not isinstance(region, str):
            raise TypeError("Region must be a string")
        if filters is not None and not isinstance(filters, list):
            raise TypeError("Filters must be a list")

        # 业务逻辑模拟
        if region == "invalid-region":
            raise ValueError({
                "Error": {
                    "Code": "InvalidZone.MismatchRegion",
                    "Message": "The specified zone does not exist."
                }
            })

        if filters and any(f.get("Name") == "invalid-filter" for f in filters):
            raise ValueError({
                "Error": {
                    "Code": "InvalidFilter",
                    "Message": "The filter is invalid."
                }
            })

        # 正常响应结构
        return {
            "Response": {
                "AccountQuotaOverview": {
                    "Region": region,
                    "PrePaidQuotaSet": [{
                        "TotalQuota": 300,
                        "UsedQuota": 5,
                        "RemainingQuota": 295,
                        "OnceQuota": 500,
                        "Zone": f"{region}-1"
                    }],
                    "PostPaidQuotaSet": [{
                        "TotalQuota": 300,
                        "UsedQuota": 5,
                        "RemainingQuota": 295,
                        "Zone": f"{region}-2"
                    }]
                },
                "RequestId": "mock-request-id",
                "AppId": 1250000000
            }
        }


# 测试用例部分
def test_normal_case():
    """测试正常请求"""
    client = TencentCloudCVMClient()
    response = client.describe_account_quota(region="ap-guangzhou")

    data = response["Response"]
    assert data["AppId"] == 1250000000
    assert len(data["AccountQuotaOverview"]["PrePaidQuotaSet"]) == 1
    assert data["AccountQuotaOverview"]["PostPaidQuotaSet"][0]["TotalQuota"] == 300


def test_invalid_region():
    """测试无效区域"""
    client = TencentCloudCVMClient()
    with pytest.raises(ValueError) as exc_info:
        client.describe_account_quota(region="invalid-region")

    error = exc_info.value.args[0]["Error"]
    assert error["Code"] == "InvalidZone.MismatchRegion"


def test_invalid_filter():
    """测试无效过滤器"""
    client = TencentCloudCVMClient()
    with pytest.raises(ValueError) as exc_info:
        client.describe_account_quota(
            region="ap-guangzhou",
            filters=[{"Name": "invalid-filter"}]
        )

    error = exc_info.value.args[0]["Error"]
    assert error["Code"] == "InvalidFilter"


def test_quota_calculation():
    """测试配额计算逻辑"""
    client = TencentCloudCVMClient()
    response = client.describe_account_quota(region="ap-shanghai")

    pre_paid = response["Response"]["AccountQuotaOverview"]["PrePaidQuotaSet"][0]
    assert pre_paid["RemainingQuota"] == pre_paid["TotalQuota"] - pre_paid["UsedQuota"]


def test_invalid_parameter_types():
    """测试参数类型错误"""
    client = TencentCloudCVMClient()

    # 测试region参数类型错误
    with pytest.raises(TypeError) as exc_info:
        client.describe_account_quota(region=123)
    assert "Region must be a string" in str(exc_info.value)

    # 测试filters参数类型错误
    with pytest.raises(TypeError) as exc_info:
        client.describe_account_quota(
            region="ap-guangzhou",
            filters="invalid_format"
        )
    assert "Filters must be a list" in str(exc_info.value)


def test_empty_filters():
    """测试空过滤器返回完整数据"""
    client = TencentCloudCVMClient()
    response = client.describe_account_quota(region="ap-beijing")

    data = response["Response"]["AccountQuotaOverview"]
    assert len(data["PrePaidQuotaSet"]) == 1
    assert len(data["PostPaidQuotaSet"]) == 1


def test_valid_filter_combinations():
    """测试有效过滤器组合"""
    client = TencentCloudCVMClient()

    response = client.describe_account_quota(
        region="ap-shanghai",
        filters=[
            {"Name": "zone", "Values": ["ap-shanghai-1"]},
            {"Name": "quota-type", "Values": ["PrePaidQuotaSet"]}
        ]
    )
    quota = response["Response"]["AccountQuotaOverview"]["PrePaidQuotaSet"][0]
    assert quota["Zone"] == "ap-shanghai-1"


# 频率限制测试
class RateLimitClient(TencentCloudCVMClient):
    def __init__(self):
        self.call_count = 0

    def describe_account_quota(self, *args, **kwargs):
        self.call_count += 1
        if self.call_count > 20:
            raise RuntimeError("API rate limit exceeded")
        return super().describe_account_quota(*args, **kwargs)


def test_rate_limit():
    """测试频率限制"""
    client = RateLimitClient()

    # 正常调用20次
    for _ in range(20):
        response = client.describe_account_quota(region="ap-guangzhou")
        assert response["Response"]["AppId"] == 1250000000

    # 第21次应触发限制
    with pytest.raises(RuntimeError) as exc_info:
        client.describe_account_quota(region="ap-guangzhou")
    assert "API rate limit exceeded" in str(exc_info.value)


def test_response_structure():
    """验证返回数据结构完整性"""
    client = TencentCloudCVMClient()
    response = client.describe_account_quota(region="ap-guangzhou")

    # 验证顶层结构
    assert "Response" in response
    assert "RequestId" in response["Response"]

    # 验证配额数据结构
    quota_data = response["Response"]["AccountQuotaOverview"]
    required_keys = ["PrePaidQuotaSet", "PostPaidQuotaSet", "Region"]
    assert all(k in quota_data for k in required_keys)

    # 验证单条配额记录结构
    sample_quota = quota_data["PrePaidQuotaSet"][0]
    assert all(k in sample_quota for k in ["TotalQuota", "UsedQuota", "RemainingQuota", "Zone"])